<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="alternate" href="/atom.xml" title="刘攀的个人专栏" type="application/atom+xml">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://liupan.run').hostname,
    root: '/',
    scheme: 'Pisces',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"right","Pisces | Gemini":240,"display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="安装pycrypto1# pip install pycrypto   RSA是一种公钥密码算法，RSA的密文是对代码明文的数字的 E 次方求mod N 的结果。也就是将明文和自己做E次乘法，然后再将其结果除以 N 求余数，余数就是密文。RSA是一个简洁的加密算法。E 和 N 的组合就是公钥（public key）。对于RSA的解密，即密文的数字的 D 次方求mod N 即可，即密文和自己做 D">
<meta name="keywords" content="python,RSA">
<meta property="og:type" content="article">
<meta property="og:title" content="008-RSA加密解密签名验签的Python操作">
<meta property="og:url" content="http:&#x2F;&#x2F;liupan.run&#x2F;2019&#x2F;12&#x2F;02&#x2F;008-RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E7%AD%BE%E5%90%8D%E9%AA%8C%E7%AD%BE%E7%9A%84Python%E6%93%8D%E4%BD%9C&#x2F;index.html">
<meta property="og:site_name" content="刘攀的个人专栏">
<meta property="og:description" content="安装pycrypto1# pip install pycrypto   RSA是一种公钥密码算法，RSA的密文是对代码明文的数字的 E 次方求mod N 的结果。也就是将明文和自己做E次乘法，然后再将其结果除以 N 求余数，余数就是密文。RSA是一个简洁的加密算法。E 和 N 的组合就是公钥（public key）。对于RSA的解密，即密文的数字的 D 次方求mod N 即可，即密文和自己做 D">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-01-02T11:44:32.577Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://liupan.run/2019/12/02/008-RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E7%AD%BE%E5%90%8D%E9%AA%8C%E7%AD%BE%E7%9A%84Python%E6%93%8D%E4%BD%9C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>008-RSA加密解密签名验签的Python操作 | 刘攀的个人专栏</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">刘攀的个人专栏</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">面朝大海,春暖花开</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">28</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">0</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">20</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://liupan.run/2019/12/02/008-RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E7%AD%BE%E5%90%8D%E9%AA%8C%E7%AD%BE%E7%9A%84Python%E6%93%8D%E4%BD%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="liupan">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="刘攀的个人专栏">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          008-RSA加密解密签名验签的Python操作
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-12-02 20:25:17" itemprop="dateCreated datePublished" datetime="2019-12-02T20:25:17+08:00">2019-12-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-01-02 19:44:32" itemprop="dateModified" datetime="2020-01-02T19:44:32+08:00">2020-01-02</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="安装pycrypto"><a href="#安装pycrypto" class="headerlink" title="安装pycrypto"></a>安装pycrypto</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># pip install pycrypto</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>RSA是一种公钥密码算法，RSA的密文是对代码明文的数字的 E 次方求mod N 的结果。也就是将明文和自己做E次乘法，然后再将其结果除以 N 求余数，余数就是密文。RSA是一个简洁的加密算法。E 和 N 的组合就是公钥（public key）。<br>对于RSA的解密，即密文的数字的 D 次方求mod N 即可，即密文和自己做 D 次乘法，再对结果除以 N 求余数即可得到明文。D 和 N 的组合就是私钥（private key）。</p>
</blockquote>
<a id="more"></a>

<h1 id="生成密钥"><a href="#生成密钥" class="headerlink" title="生成密钥"></a>生成密钥</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> Crypto <span class="keyword">import</span> Random</span><br><span class="line"><span class="keyword">from</span> Crypto.Hash <span class="keyword">import</span> SHA</span><br><span class="line"><span class="keyword">from</span> Crypto.Cipher <span class="keyword">import</span> PKCS1_v1_5 <span class="keyword">as</span> Cipher_pkcs1_v1_5</span><br><span class="line"><span class="keyword">from</span> Crypto.Signature <span class="keyword">import</span> PKCS1_v1_5 <span class="keyword">as</span> Signature_pkcs1_v1_5</span><br><span class="line"><span class="keyword">from</span> Crypto.PublicKey <span class="keyword">import</span> RSA</span><br></pre></td></tr></table></figure>


<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">random_generator=Random.new().read</span><br><span class="line">rsa=RSA.generate(<span class="number">1024</span>,random_generator)</span><br><span class="line">private_pem=rsa.exportKey()</span><br><span class="line">print(private_pem)</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'master-private.pem'</span>,<span class="string">'wb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(private_pem)</span><br><span class="line"></span><br><span class="line">public_pem=rsa.publickey().exportKey()</span><br><span class="line">print(public_pem)</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'master-public.pem'</span>,<span class="string">'wb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(public_pem)</span><br></pre></td></tr></table></figure>

<pre><code>b&apos;-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQDwZAC/MBMX/2PgvzhYHXQSoHyWL6s+XuQhWg2qlMPZwhCmOBXH\njCJ+vPS7olOQJziLq9Qy2Wyk4mlx5EBjv5DbOv1wRJzu7JqD7hPTJX2YqoyHD3vH\n1YvQs2Inm8IXtanDdwGWn9/5z2ob/1sn1AL/cZLd1W5F2gJ23cdWKPa5zQIDAQAB\nAoGAOEZQ3nD0p1OEICLjn80VVR74y3fRUMKKCTy5oks9JgcGOsM6ZgJqON0nNZ2k\njkSAOkI5ZMX9ZwQRxzW11SQNVrDncezxidSNtUuCbK8b1XmjEQmZ5zbg0nlxm6ya\nT7OWhoHrcwu3RdMeduDqLvXi9r80NXjiQMrGCA0m6Gt1+wECQQDzb6mzcVCLhS2h\n1MgTkJo2wxsl7cXK+8X3vrfBX73lcIgqYea6x9zFEcu9ipV+R+da474ww/0tnTmB\nw5ZOvVZtAkEA/MwZ/d+VVXGuYXnPEvwrLiElfD6I2lbAkzCM4jGOJJ5hxTL6GIQM\nLkhC6yD3yTNkJEAurQvWQWxNBlTijbpU4QJBAIus/x7RnphfEr6vGxl2t7VCHzqV\nAg8khQNQb5jJeWjDN62xvLRg5sBAJLmdYYcydIGG+OJ8IbFha9STx5NoOcUCQQCu\nbZYxmihMQJh2IbpD+0NAHRbkV7HOFbXi2ckb+d1+XtpPWxE+AT72YF3sJ19RsOgU\nK0UJmfVIRxYOnFuGN1+BAkAU5NO71Ke1YE0vCFcTeLRGdESrh923IOQV2lkifMhL\nmNWRywxf3fs0QtbNnSMTLIOvitDen1/Y5HeKPoJ0lK1E\n-----END RSA PRIVATE KEY-----&apos;
b&apos;-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwZAC/MBMX/2PgvzhYHXQSoHyW\nL6s+XuQhWg2qlMPZwhCmOBXHjCJ+vPS7olOQJziLq9Qy2Wyk4mlx5EBjv5DbOv1w\nRJzu7JqD7hPTJX2YqoyHD3vH1YvQs2Inm8IXtanDdwGWn9/5z2ob/1sn1AL/cZLd\n1W5F2gJ23cdWKPa5zQIDAQAB\n-----END PUBLIC KEY-----&apos;</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">rsa=RSA.generate(<span class="number">1024</span>,random_generator)</span><br><span class="line">private_pem=rsa.exportKey()</span><br><span class="line">print(private_pem)</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'ghost-private.pem'</span>,<span class="string">'wb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(private_pem)</span><br><span class="line">    </span><br><span class="line">public_pem=rsa.publickey().exportKey()</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'ghost-public.pem'</span>,<span class="string">'wb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(public_pem)</span><br><span class="line">print(public_pem)</span><br></pre></td></tr></table></figure>

<pre><code>b&apos;-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC28f7fspTu02tYk5H53uVi3mb07XOfhx5ud/ctKsgfKSqbiACZ\nh9gSDMcqa2csAymW/TShGTrt2wRo2/UR6puYGpsWD6Az9PG/Nut4IlOS2WRXAhFp\n3EfQNaJKeWTwrtnAjvLA18Aze0IOqUkHdRV4lSkuq7kkx3a5mbIl08uHFwIDAQAB\nAoGAWtRHMJUfcHuzPiT2QtKxnKbDAzOpRjj1mO8i31/wP9hWeSXK9m8FjeCeOadd\nb/KaAYbxTFKUeWdWByG9yQlr+f1kewFIrD176I0RcjTJg7xiHRdhxr6nROCPMqyb\nS82W6IwReJO81g2qu8Xev+VlBAavBQpy/Le+a/5iYMzJ+yECQQC6er55bk1aEQbj\nvIFLzHs118buM/s0Q+SGz95kU5EFXpj6EVZ9sy/MVLuL7LjKzguigG3SW1my9Kra\ngsjgjrlZAkEA+yX04U2BKEZ/IndugRYfmg/Q+XxL3KJxd474aZ1aXjJ0rXWLOrXf\nhPBNljhuq3/LZPgP6HzoqDEl4ydAAOPF7wJBAKCVWrlPFyVcTEaI6f7QE7oGGrS9\n5rDXVlARaT2UCOpK0AloLMcKKzsWLHsOWwOp87L4TZo8OD43G3oX7cwSm+ECQQCu\n6kSfFie6MT8idiPUa+AeoJ1e5R7Az7JPHpgMlrb1nBZ/KLqLbVf7cpHW6f7KGvtB\nmzMZLMWtPm2wwwlklT6pAkBB2tEJjw4P/9irlMlOKH2kWJP7cFrhSleWChS8R/4E\n8Mo61IANEsC1tmR4XrWJVn1A5z/Q+Z8Sl4l7H2lOQAxb\n-----END RSA PRIVATE KEY-----&apos;
b&apos;-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC28f7fspTu02tYk5H53uVi3mb0\n7XOfhx5ud/ctKsgfKSqbiACZh9gSDMcqa2csAymW/TShGTrt2wRo2/UR6puYGpsW\nD6Az9PG/Nut4IlOS2WRXAhFp3EfQNaJKeWTwrtnAjvLA18Aze0IOqUkHdRV4lSku\nq7kkx3a5mbIl08uHFwIDAQAB\n-----END PUBLIC KEY-----&apos;</code></pre><h1 id="加密解密"><a href="#加密解密" class="headerlink" title="加密解密"></a>加密解密</h1><blockquote>
<p>通常通信的时候，发送者使用接受者的公钥加密，接受者使用接受者私钥解密。<br>简而言之，Master给Ghost通信，需要加密内容，那么Ghost会生成一个秘钥对，Ghost的公钥ghost-public.pem和私钥ghost-private.pem 。Ghost 把公钥公开给发送者，任何人都可以用来加密，然后Master使用ghost-public.pem进行加密，然后把内容发给Ghost，Ghost再使用ghost-private.pem进行解密。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> base64</span><br><span class="line">message=<span class="string">'hello ghost ,this is for you'</span></span><br><span class="line">print(<span class="string">'原文:'</span>,message)</span><br><span class="line">encrypt_text=<span class="string">''</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'ghost-public.pem'</span>,<span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    key=f.read()</span><br><span class="line">    rsakey=RSA.importKey(key)</span><br><span class="line">    cipher=Cipher_pkcs1_v1_5.new(rsakey)</span><br><span class="line">    cipher_text=base64.b64encode(cipher.encrypt(message.encode(encoding=<span class="string">"utf-8"</span>)))<span class="comment"># 注意需要编码</span></span><br><span class="line">    encrypt_text=cipher_text</span><br><span class="line">    print(<span class="string">'密文(已经base64编号):'</span>,cipher_text)</span><br></pre></td></tr></table></figure>

<pre><code>原文: hello ghost ,this is for you
密文(已经base64编号): b&apos;NhALn+Y83N9PCerbHhOBkSdhNR6tIiOt3+2CFEy3C4fmdThIGqBW8g1qH68MdpljE9mVHAK/xEZso2SIkxpJ3RjCPRMo0y2bPHmu5JcY4E7wLgarRy7kmUIPEZ2LJOpd5XvTgGCFmjNP1bzYnpt5GX+ggs69lDPDf23+ueZ3byk=&apos;</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> open(<span class="string">'ghost-private.pem'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    key=f.read()</span><br><span class="line">    rsakey=RSA.importKey(key)</span><br><span class="line">    cipher=Cipher_pkcs1_v1_5.new(rsakey)</span><br><span class="line">    print(encrypt_text)</span><br><span class="line">    text=cipher.decrypt(base64.b64decode(encrypt_text),random_generator)</span><br><span class="line">    print(<span class="string">"解密后"</span>,text)</span><br></pre></td></tr></table></figure>

<pre><code>b&apos;NhALn+Y83N9PCerbHhOBkSdhNR6tIiOt3+2CFEy3C4fmdThIGqBW8g1qH68MdpljE9mVHAK/xEZso2SIkxpJ3RjCPRMo0y2bPHmu5JcY4E7wLgarRy7kmUIPEZ2LJOpd5XvTgGCFmjNP1bzYnpt5GX+ggs69lDPDf23+ueZ3byk=&apos;
解密后 b&apos;hello ghost ,this is for you&apos;</code></pre><h1 id="签名与验签"><a href="#签名与验签" class="headerlink" title="签名与验签"></a>签名与验签</h1><blockquote>
<p>对于窃听者，有时候也可以对伪造Master给Ghost发送内容。为此出现了数字签名。也就是Master给Ghost发送消息的时候，先对消息进行签名，表明自己的身份，并且这个签名无法伪造。具体过程即Master使用自己的私钥对内容签名，然后Ghost使用Master的公钥进行验签。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 签名</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'master-private.pem'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    key=f.read()</span><br><span class="line">    rsakey=RSA.importKey(key)</span><br><span class="line">    signer=Signature_pkcs1_v1_5.new(rsakey)</span><br><span class="line">    digest=SHA.new()</span><br><span class="line">    digest.update(message.encode(<span class="string">'utf8'</span>))</span><br><span class="line">    sign=signer.sign(digest)</span><br><span class="line">    signature=base64.b64encode(sign)</span><br><span class="line">print(signature)</span><br></pre></td></tr></table></figure>

<pre><code>b&apos;UWi0CNGCy4uP/Sy+H0941rfpZD3GR90gafiCEx3W2VUw8eHE4pUaxweBKFKHyyJiJlN7iDtmoAyPr/rYgNM7TnQ7Aj5DQvhlvZDOla8TuaWXpTc95t7VTvKaxdOlJE752FFrVytKgfUUoN9Ud1OxcIOZpyFuS0OMM1/iJGiaflY=&apos;</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 验签</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'master-public.pem'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    key=f.read()</span><br><span class="line">    rsakey=RSA.importKey(key)</span><br><span class="line">    digest=SHA.new()</span><br><span class="line">    digest.update(message.encode(<span class="string">'utf8'</span>))</span><br><span class="line">    verifier=Signature_pkcs1_v1_5.new(rsakey)</span><br><span class="line">    is_verify=verifier.verify(digest,base64.b64decode(signature))</span><br><span class="line">    print(is_verify)</span><br></pre></td></tr></table></figure>

<pre><code>True</code></pre><h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><blockquote>
<p>Pycrypto提供了比较完善的加密算法。RSA广泛用于加密与解密，还有数字签名通信领域。使用Publick/Private秘钥算法中，加密主要用对方的公钥，解密用自己的私钥。签名用自己的私钥，验签用对方的公钥。</p>
</blockquote>
<blockquote>
<p><strong>加密解密：公钥加密，私钥解密</strong></p>
</blockquote>
<blockquote>
<p><strong>签名验签：私钥签名，公钥验签</strong></p>
</blockquote>
<blockquote>
<p>无论是加密机密还是签名验签都使用同一对秘钥对，</p>
</blockquote>
<table>
<thead>
<tr>
<th align="left">Format</th>
<th align="left">Name</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody><tr>
<td align="left">PKCS #7</td>
<td align="left">Cryptographic Message Syntax Standard</td>
<td align="left">A PKCS #7 file can be used to store certificates, which is a SignedData structure without data (just the certificates). The file name extension is usually <code>.p7b</code>, <code>.p7c</code></td>
</tr>
<tr>
<td align="left">PKCS #8</td>
<td align="left">Private-Key Information Syntax Standard.</td>
<td align="left">Used to carry private certificate keypairs (encrypted or unencrypted).</td>
</tr>
<tr>
<td align="left">PKCS #12</td>
<td align="left">Personal Information Exchange Syntax Standard.</td>
<td align="left">Defines a file format commonly used to store private keys with accompanying public key certificates, protected with a password-based symmetric key. It is the successor to PFX from Microsoft.</td>
</tr>
<tr>
<td align="left">DER</td>
<td align="left">Distinguished Encoding Rules</td>
<td align="left">A binary format for keys or certificates. It is a message transfer syntax specified by the ITU in X.690.</td>
</tr>
<tr>
<td align="left">PEM</td>
<td align="left">Privacy Enhanced Mail</td>
<td align="left">Base64 encoded DER certificates or keys, with additional header and footer lines.   The PEM private key format uses the header and footer lines:  <code>-----BEGIN RSA PRIVATE KEY-----</code>  <code>-----END RSA PRIVATE KEY-----</code>   The PEM public key format uses the header and footer lines:  <code>-----BEGIN PUBLIC KEY-----</code>  <code>-----END PUBLIC KEY-----</code>   The PEM certificate uses the header and footer lines:  <code>-----BEGIN CERTIFICATE-----</code>  <code>-----END CERTIFICATE-----</code></td>
</tr>
</tbody></table>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/python/" rel="tag"># python</a>
              <a href="/tags/RSA/" rel="tag"># RSA</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/11/30/002-Hexo%E4%BD%BF%E7%94%A8%E5%8F%8A%E4%B8%BB%E9%A2%98%E9%85%8D%E7%BD%AE/" rel="prev" title="002-Hexo使用及主题配置">
      <i class="fa fa-chevron-left"></i> 002-Hexo使用及主题配置
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/12/10/003-Flask%E5%90%8E%E7%AB%AF-Vue%E5%89%8D%E7%AB%AF-Webpack%E5%88%9B%E5%BB%BA%E5%BA%94%E7%94%A8-01/" rel="next" title="003-Flask后端-Vue前端-Webpack创建应用-01">
      003-Flask后端-Vue前端-Webpack创建应用-01 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#安装pycrypto"><span class="nav-text">安装pycrypto</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#生成密钥"><span class="nav-text">生成密钥</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#加密解密"><span class="nav-text">加密解密</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#签名与验签"><span class="nav-text">签名与验签</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="liupan"
      src="/images/avatar.gif">
  <p class="site-author-name" itemprop="name">liupan</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">20</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">28</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/facetothesea" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;facetothesea" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:hbxgliupan@sina.com" title="E-Mail → mailto:hbxgliupan@sina.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">liupan</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.5.0
  </div>

        








        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>













  

  

  

</body>
</html>
